<?php

namespace app\admin\controller;

use app\admin\service\RatingScaleImportService;
use app\admin\service\RatingScaleService;
use app\BaseController;
use app\common\formula\FormulaType;
use app\model\RatingScaleFactorLevelModel;
use app\model\RatingScaleFactorModel;
use app\model\RatingScaleFactorWarningModel;
use app\model\RatingScaleModel;
use app\model\RatingScaleModeModel;
use app\model\RatingScalePackInfoModel;
use app\model\RatingScalePackModel;
use app\model\RatingScaleQuestionAnswerModel;
use app\model\RatingScaleQuestionModel;
use app\model\RatingScaleQuestionRelatedFactorModel;
use app\model\RatingScaleTypeModel;
use app\model\TaskModel;
use app\model\TaskRatingScaleModel;
use app\model\UserModel;
use think\App;

class RatingScale extends BaseController
{
    protected $mode;

    public function __construct(App $app)
    {
        parent::__construct($app);
        $this->mode = new RatingScaleModel();
    }

    /**
     * 新增量表-职业测评
     * @return false|string
     */
    public function metierAdd(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param('data');
            if (empty($param)) throw new \Exception('参数错误！');
            $nameArr = array_column($param, 'name');
            if (!empty($nameArr)){
                $is_repeat = $this->mode->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['name', 'in', $nameArr]
                ])->field('id,name')->find();
                if ($is_repeat) throw new \Exception($is_repeat['name'].'量表名称重复！');
            }
            $RatingScaleImportService = new RatingScaleImportService($this->app);
            foreach ($param as $item) {
                if (!$RatingScaleImportService->import($item['file'], [
                    'company_id' => $this->userData['company_id'],
                    'areas_id' => $this->userData['areas_id'],
                    'unit_id' => $this->userData['unit_id'],
                    'uid' => $this->userData['id'],
                    'name' => $item['name'],
                    'type_id' => $item['type_id'],
                    'cover' => $item['cover']??''
                ],5)) throw new \Exception($RatingScaleImportService->message.'line:'.$RatingScaleImportService->line);
            }
            $this->mode->commit();
            return success([],'添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }

    }


    /**
     * 量表类型选择器
     * @return false|string
     */
    public function typeSelector(): bool|string
    {
        try {
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $where[] = ['status','=',1];
            $RatingScaleTypeModel = new RatingScaleTypeModel();
            $list = $RatingScaleTypeModel->field('id,name')->where($where)->order('sort','asc')->select()->toArray();
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 量表包选择器
     * @return bool|string
     */
    public function packSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['use_scene'])) {
                foreach ($param['use_scene'] as $value) {
                    $RatingScaleWhere[] = ['use_scene', '=',  trim($value),'or'];
                }
            }
            $RatingScaleWhere[] = ['unit_id', '=', $this->userData['unit_id']];
            $RatingScaleWhere[] = ['status', '=', 1];
            $rating_scale_id = $this->mode->where($RatingScaleWhere)->column('id');
            if (!empty($rating_scale_id)) {
                $RatingScalePackModel = new RatingScalePackModel();
                $pack_info_id = $RatingScalePackModel->where('rating_scale_id','in', $rating_scale_id)->column('pack_info_id');
                if (!empty($pack_info_id)){
                    $where[] = ['id','in', $pack_info_id];
                }else{
                    $where[] = ['id','=',-1];
                }
            }else{
                $where[] = ['id','=',-1];
            }
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $where[] = ['status', '=', 1];
            $RatingScalePackInfoModel = new RatingScalePackInfoModel();
            $list = $RatingScalePackInfoModel->field('id,name')
                ->where($where)->withCount('RatingScalePack')->select()->toArray();
            foreach ($list as $key => $item) {
                if ($item['rating_scale_pack_count'] == 0) {
                    unset($list[$key]);
                }
            }
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 量表选择器
     * @return bool|string
     */
    public function selector(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $RatingScaleWhere = [];
            if (!empty($param['name'])) {
                $RatingScaleWhere[] = ['name', 'like', '%' . $param['name'] . '%'];
            }
            if (!empty($param['use_scene'])) {
                foreach ($param['use_scene'] as $value) {
                    $RatingScaleWhere[] = ['use_scene', '=',  trim($value),'or'];
                }
            }
            $RatingScaleWhere[] = ['unit_id', '=', $this->userData['unit_id']];
            $RatingScaleWhere[] = ['status', '=', 1];
            $type_id = $this->mode->where($RatingScaleWhere)->column('type_id');
            if (!empty($type_id)) {
                $where[] = ['id', 'in', $type_id];
            }else{
                $where[] = ['id', '=', -1];
            }
            $where[] = ['unit_id', '=', $this->userData['unit_id']];
            $where[] = ['status', '=', 1];
            $RatingScaleTypeModel = new RatingScaleTypeModel();
            $list = $RatingScaleTypeModel->field('id,name')
                ->where($where)
                ->with([
                    'RatingScale' => function ($query) {
                        $query->field('id,type_id,name,mode_id');
                    }
                ])->select()->toArray();
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(), [
                'line' => $e->getLine(),
                'file' => $e->getFile()
            ]);
        }
    }

    /**
     * 预警列表符号列表
     * @return string|false
     */
    public function getSymbolList(): bool|string
    {
        try {
            $RatingScaleService = new RatingScaleService($this->app);
            $list = $RatingScaleService->getSymbolList();
            $data = [];
            foreach ($list as $key => $value) {
                $data[] = [
                    'id' => $key,
                    'value' => $value,
                ];
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 预警标志
     * @return string|false
     */
    public function getFactorWarningMark(): bool|string
    {
        try {
            $RatingScaleService = new RatingScaleService($this->app);
            $list = $RatingScaleService->getFactorWarningMark();
            $data = [];
            foreach ($list as $key => $value) {
                $data[] = [
                    'id' => $key,
                    'value' => $value,
                ];
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 因子预警颜色
     * @return string|false
     */
    public function getFactorWarningColor(): bool|string
    {
        try {
            $RatingScaleService = new RatingScaleService($this->app);
            $list = $RatingScaleService->getFactorWarningColor();
            $data = [];
            foreach ($list as $key => $value) {
                $data[] = [
                    'id' => $key,
                    'value' => $value,
                ];
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 预警程度（等级）
     * @return array|string
     */
    public function getFactorLevel(): array|string
    {
        try {
            $RatingScaleService = new RatingScaleService($this->app);
            $list = $RatingScaleService->getFactorLevel();
            $data = [];
            foreach ($list as $key => $value) {
                $data[] = [
                    'id' => $key,
                    'value' => $value,
                ];
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 因子计算公式选择器
     * @return string|false
     */
    public function factorFormulaSelector(): bool|string
    {
        try {
            $FormulaType = new FormulaType();
            return success($FormulaType->getFormulaList());
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 量表类型导航
     * @return false|string
     */
    public function typeNav(): bool|string
    {
        try {
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $where[] = ['status','=',1];
            $RatingScaleTypeModel = new RatingScaleTypeModel();
            $list = $RatingScaleTypeModel->field('id,name')->where($where)->withCount('RatingScale')->order('sort','asc')->select()->toArray();
            return success($list);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 量表选择器
     * @return false|string
     */
    public function ratingScaleSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['type_id'])) {
                $where[] = ['type_id', '=', $param['type_id']];
            }
            $where[] = ['status','=',1];
            $where[] = ['channel','=',1];
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $data = $this->mode->where($where)->field('id,name,mode_id')->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 批量修改字段状态
     * @return false|string
     */
    public function updateAll(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $field = $this->request->param('field');
            $status = $this->request->param('status');
            if (!is_array($id)) throw new \Exception('格式错误！');
            $update = match ($field) {
                'is_self_evaluation' => [
                    'is_self_evaluation' => $status,
                    'self_evaluation_time' => time()
                ],
                default => [
                    $field => $status
                ],
            };
            $this->mode->where('id','in',$id)->update($update);
            return success([],'修改成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 量表模板选择器
     * @return false|string
     */
    public function modeSelector(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $RatingScaleModeModel = new RatingScaleModeModel();
            $data = $RatingScaleModeModel->field('id,name')->where('rating_scale_id','=',$id)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 量表列表
     * @return false|string
     */
    public function list(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['type_id'])) {
                $where[] = ['type_id', '=', $param['type_id']];
            }
            if (!empty($param['name'])) {
                $where[] = ['name', 'like', '%'.$param['name'].'%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            }else{
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (isset($param['status']) && strlen($param['status']) > 0) {
                $where[] = ['status', '=', $param['status']];
            }
            if (isset($param['is_self_evaluation']) && strlen($param['is_self_evaluation']) > 0) {
                $where[] = ['is_self_evaluation', '=', $param['is_self_evaluation']];
            }
            if (isset($param['is_recommend']) && strlen($param['is_recommend']) > 0) {
                $where[] = ['is_recommend', '=', $param['is_recommend']];
            }
            if (isset($param['use_price']) && strlen($param['use_price']) > 0) {
                if ($param['use_price'] == 1){
                    $where[] = ['use_price', '>', 0];
                }else{
                    $where[] = ['use_price', '=', 0];
                }
            }
            if (isset($param['interpret_price']) && strlen($param['interpret_price']) > 0) {
                if ($param['interpret_price'] == 1){
                    $where[] = ['interpret_price', '>', 0];
                }else{
                    $where[] = ['interpret_price', '=', 0];
                }
            }
            $where[] = ['channel','=',1];
            $where[] = ['unit_id','=',$this->userData['unit_id']];
            $query = $this->mode->where($where);
            $data = $query->order('id desc')->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 新增量表
     * @return false|string
     */
    public function add(): bool|string
    {
        $this->mode->startTrans();
        try {
            $param = $this->request->param('data');
            if (empty($param)) throw new \Exception('参数错误！');
            $nameArr = array_column($param, 'name');
            if (!empty($nameArr)){
                $is_repeat = $this->mode->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['name', 'in', $nameArr]
                ])->field('id,name')->find();
                if ($is_repeat) throw new \Exception($is_repeat['name'].'量表名称重复！');
            }
            $RatingScaleImportService = new RatingScaleImportService($this->app);
            foreach ($param as $item) {
                if (!$RatingScaleImportService->import($item['file'], [
                    'company_id' => $this->userData['company_id'],
                    'areas_id' => $this->userData['areas_id'],
                    'unit_id' => $this->userData['unit_id'],
                    'uid' => $this->userData['id'],
                    'name' => $item['name'],
                    'type_id' => $item['type_id'],
                    'cover' => $item['cover']??''
                ])) throw new \Exception($RatingScaleImportService->message.'line:'.$RatingScaleImportService->line);
            }
            $this->mode->commit();
            return success([],'添加成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }

    }

    /**
     * 更新量表
     * @return false|string
     */
    public function update(): bool|string
    {
        try {
            $param = $this->request->param();
            $info = $this->mode->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            if (!empty($param['name']) && $param['name'] != $info['name']) {
                $is = $this->mode->where([
                    ['unit_id','=',$this->userData['unit_id']],
                    ['name','=',$param['name']]
                ])->value('id');
                if ($is) throw new \Exception('量表名称已存在！');
            }
            $info->save($param);
            return success([],'更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除量表
     * @return false|string
     */
    public function del(): bool|string
    {
        $this->mode->startTrans();
        try {
            $id = $this->request->param('id');
            $TaskRatingScaleModel = new TaskRatingScaleModel();
            $RatingScalePackModel = new RatingScalePackModel();
            $TaskModel = new TaskModel();
            $task_id = $TaskModel->where('unit_id','=',$this->userData['unit_id'])->column('id');
            if (!empty($task_id)){
                if (is_array($id)){
                    $is_task = $TaskRatingScaleModel->where([
                        ['task_id','in',$task_id],
                        ['rating_scale_id','in',$id]
                    ])->value('id');
                    if ($is_task) throw new \Exception('有任务正在使用该量表无法删除！');
                    $this->mode->where('id','in',$id)->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                    //同时删除量表包里的量表
                    $RatingScalePackModel->where('rating_scale_id','in',$id)->update([
                        'is_del' => 1,
                    ]);
                }else{
                    $is_task = $TaskRatingScaleModel->where([
                        ['task_id','in',$task_id],
                        ['rating_scale_id','=',$id]
                    ])->value('id');
                    if ($is_task) throw new \Exception('有任务正在使用该量表无法删除！');
                    $this->mode->where('id','=',$id)->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                    //同时删除量表包里的量表
                    $RatingScalePackModel->where('rating_scale_id','=',$id)->update([
                        'is_del' => 1,
                    ]);
                }
            }else{
                if (is_array($id)){
                    $this->mode->where('id','in',$id)->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                    //同时删除量表包里的量表
                    $RatingScalePackModel->where('rating_scale_id','in',$id)->update([
                        'is_del' => 1,
                    ]);
                }else{
                    $this->mode->where('id','=',$id)->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                    //同时删除量表包里的量表
                    $RatingScalePackModel->where('rating_scale_id','=',$id)->update([
                        'is_del' => 1,
                    ]);
                }
            }
            $this->mode->commit();
            return success([],'删除成功！');
        } catch (\Exception $e) {
            $this->mode->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 量表基本信息
     * @return false|string
     */
    public function info(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $info = $this->mode->with(['ratingScaleTypeName'])->find($id);
            return success($info);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取量表题目
     * @return false|string
     */
    public function getRatingScaleQuestion(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $RatingScaleService = new RatingScaleService($this->app);
            return success($RatingScaleService->GetQuestion($id));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取题目详情
     * @return false|string
     */
    public function getRatingScaleQuestionInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $RatingScaleService = new RatingScaleService($this->app);
            return success($RatingScaleService->GetQuestionInfo($id));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 量表题目列表
     * @return false|string
     */
    public function questionList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            $RatingScaleQuestion = new RatingScaleQuestionModel();
            $RatingScaleQuestionRelatedFactor = new RatingScaleQuestionRelatedFactorModel();
            if (isset($param['rating_scale_id']) && !empty($param['rating_scale_id'])) {
                $where[] = ['rating_scale_id','=',$param['rating_scale_id']];
            }
            if (isset($param['name']) && !empty($param['name'])) {
                $where[] = ['name', 'like', '%'.$param['name'].'%'];
            }
            if (isset($param['type']) && !empty($param['type'])) {
                $where[] = ['type','=',$param['type']];
            }
            if (isset($param['factor_id']) && !empty($param['factor_id'])) {
                $question_ids = $RatingScaleQuestionRelatedFactor->where('factor_id','=',$param['factor_id'])->column('question_id');
                if (count($question_ids)>0) {
                    $where[] = ['id','in',$question_ids];
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            $data = $RatingScaleQuestion->where($where)->paginate($param['pageSize']);
            $data = $data?$data->toArray():['data'=>[]];
            $QuestionIds = array_column($data['data'],'id');
            $RelatedFactorList = $RatingScaleQuestionRelatedFactor->with('factorName')->where('question_id','in',$QuestionIds)->select()->toArray();
            $RelatedFactorData = [];
            foreach ($RelatedFactorList as $factor) {
                $RelatedFactorData[$factor['question_id']][] = $factor['factor_name'];
            }
            foreach ($data['data'] as &$item) {
                $item['child'] = $RelatedFactorData[$item['id']]??[];
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 新增量表题目
     * @return false|string
     */
    public function addQuestion(): bool|string
    {
        $RatingScaleQuestion = new RatingScaleQuestionModel();
        $RatingScaleQuestion->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'rating_scale_id|量表ID' => 'require',
                'num|题号' => 'require|gt:0',
                'name|题目名称' => 'require',
                'type|题目类型' => 'require',
                'answer|答案' => 'require',
                'factor|因子' => 'require'
            ]);
            if (isset($param['answer'])){
                $answer = $param['answer'];
                unset($param['answer']);
            }
            if (isset($param['factor'])){
                $factor = $param['factor'];
                unset($param['factor']);
            }
            $QuestionId = $RatingScaleQuestion->insertGetId($param);
            //答案
            if (isset($answer)){
                $answerData = [];
                foreach ($answer as $item){
                    $answerData[] = [
                        'rating_scale_id' => $param['rating_scale_id'],
                        'question_id' => $QuestionId,
                        'name' => $item['name'],
                        'score' => $item['score']
                    ];
                }
                if (count($answerData) > 0){
                    $RatingScaleQuestionAnswer = new RatingScaleQuestionAnswerModel();
                    $RatingScaleQuestionAnswer->insertAll($answerData);
                }
            }
            //关联因子
            if (isset($factor)){
                $factorData = [];
                foreach ($factor as $item){
                    $factorData[] = [
                        'rating_scale_id' => $param['rating_scale_id'],
                        'question_id' => $QuestionId,
                        'factor_id' => $item['factor_id']
                    ];
                }
                if (count($factorData) > 0){
                    $RatingScaleQuestionRelatedFactor = new RatingScaleQuestionRelatedFactorModel();
                    $RatingScaleQuestionRelatedFactor->insertAll($factorData);
                }
            }
            $RatingScaleQuestion->commit();
            return success([],'添加成功！');
        } catch (\Exception $e) {
            $RatingScaleQuestion->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }

    }

    /**
     * 编辑量表题目
     * @return false|string
     */
    public function updateQuestion(): bool|string
    {
        $RatingScaleQuestion = new RatingScaleQuestionModel();
        $RatingScaleQuestion->startTrans();
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'num|题号' => 'require|gt:0',
                'name|题目名称' => 'require',
                'type|题目类型' => 'require',
                'answer|答案' => 'require',
                'factor|因子' => 'require'
            ]);
            $QuestionId = $param['id'];
            unset($param['id']);
            if (isset($param['answer'])){
                $answer = $param['answer'];
                unset($param['answer']);
            }
            if (isset($param['factor'])){
                $factor = $param['factor'];
                unset($param['factor']);
            }
            $info = $RatingScaleQuestion->find($QuestionId);
            $info->save($param);
            //答案
            if (isset($answer)){
                $answerData = [];
                foreach ($answer as $item){
                    $answerData[] = [
                        'rating_scale_id' => $info['rating_scale_id'],
                        'question_id' => $QuestionId,
                        'name' => $item['name'],
                        'score' => $item['score']
                    ];
                }
                if (count($answerData) > 0){
                    $RatingScaleQuestionAnswer = new RatingScaleQuestionAnswerModel();
                    $RatingScaleQuestionAnswer->where('question_id','=',$QuestionId)->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                    $RatingScaleQuestionAnswer->insertAll($answerData);
                }
            }
            //关联因子
            if (isset($factor)){
                $factorData = [];
                foreach ($factor as $item){
                    $factorData[] = [
                        'rating_scale_id' => $info['rating_scale_id'],
                        'question_id' => $QuestionId,
                        'factor_id' => $item['factor_id']
                    ];
                }
                if (count($factorData) > 0){
                    $RatingScaleQuestionRelatedFactor = new RatingScaleQuestionRelatedFactorModel();
                    $RatingScaleQuestionRelatedFactor->where('question_id','=',$QuestionId)->update([
                        'is_del' => 1,
                        'del_time' => time()
                    ]);
                    $RatingScaleQuestionRelatedFactor->insertAll($factorData);
                }
            }
            $RatingScaleQuestion->commit();
            return success([],'更新成功！');
        } catch (\Exception $e) {
            $RatingScaleQuestion->rollback();
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除量表题目
     * @return false|string
     */
    public function delQuestion(): bool|string
    {
        $id = $this->request->param('id');
        try {
            $RatingScaleQuestion = new RatingScaleQuestionModel();
            $RatingScaleQuestion->where('id','=',$id)->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success([],'删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 因子选择器
     * @return false|string
     */
    public function factorSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (isset($param['rating_scale_id']) && strlen($param['rating_scale_id']) > 0){
                $where[] = ['rating_scale_id','=',$param['rating_scale_id']];
            }
            if (isset($param['mode_id']) && strlen($param['mode_id']) > 0){
                $where[] = ['mode_id','=',$param['mode_id']];
            }
            $RatingScaleFactor = new RatingScaleFactorModel();
            $data = $RatingScaleFactor->field('id,name')
                ->where($where)->select()->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 因子等级选择器
     * @return false|string
     */
    public function factorLevelSelector(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (isset($param['factor_id']) && $param['factor_id']){
                $where[] = ['factor_id','=',$param['factor_id']];
            }
            $RatingScaleFactorLevelModel = new RatingScaleFactorLevelModel();
            $data = $RatingScaleFactorLevelModel->field('id,level')
                ->where($where)->select()->toArray();
            $RatingScaleService = new RatingScaleService($this->app);
            foreach ($data as &$item){
                $item['level_name'] = $RatingScaleService->getFactorLevelName($item['level']);
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取因子详情
     * @return false|string
     */
    public function getFactorInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $RatingScaleService = new RatingScaleService($this->app);
            return success($RatingScaleService->getFactorInfo($id));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 因子列表
     * @return false|string
     */
    public function factorList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (isset($param['rating_scale_id']) && $param['rating_scale_id']){
                $where[] = ['rating_scale_id','=',$param['rating_scale_id']];
            }
            if (isset($param['mode_id']) && $param['mode_id']){
                $where[] = ['mode_id','=',$param['mode_id']];
            }
            $RatingScaleFactor = new RatingScaleFactorModel();
            $data = $RatingScaleFactor->where($where)->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 新增因子
     * @return false|string
     */
    public function addFactor(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'mode_id|模板ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'name|因子名称' => 'require',
                'formula_method|因子计分方式' => 'require',
                'is_show|是否显示' => 'require',
                'factor_explain|因子解释' => 'require',
            ]);
            $RatingScaleFactor = new RatingScaleFactorModel();
            $RatingScaleFactor->insert($param);
            return success([],'添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑因子
     * @return false|string
     */
    public function updateFactor(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'mode_id|模板ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'name|因子名称' => 'require',
                'formula_method|因子计分方式' => 'require',
                'is_show|是否显示' => 'require',
                'factor_explain|因子解释' => 'require',
            ]);
            $RatingScaleFactor = new RatingScaleFactorModel();
            $info = $RatingScaleFactor->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save($param);
            return success([],'更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除因子
     * @return false|string
     */
    public function delFactor(): bool|string
    {
        $id = $this->request->param('id');
        try {
            $RatingScaleFactor = new RatingScaleFactorModel();
            $RatingScaleFactor->where('id','=',$id)->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success([],'删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取因子等级定义详情
     * @return false|string
     */
    public function getFactorLevelInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $RatingScaleFactorLevel = new RatingScaleFactorLevelModel();
            return success($RatingScaleFactorLevel->find($id));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 因子等级定义列表
     * @return false|string
     */
    public function factorLevelList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (isset($param['rating_scale_id']) && $param['rating_scale_id']){
                $where[] = ['rating_scale_id','=',$param['rating_scale_id']];
            }
            if (isset($param['mode_id']) && $param['mode_id']){
                $where[] = ['mode_id','=',$param['mode_id']];
            }
            $RatingScaleFactorLevel = new RatingScaleFactorLevelModel();
            $data = $RatingScaleFactorLevel->where($where)
                ->with(['factorName'])
                ->order('id desc')->paginate($param['pageSize'])->toArray();
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 添加因子等级
     * @return false|string
     */
    public function addFactorLevel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'mode_id|模板ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'factor_id|因子' => 'require',
                'level|程度等级' => 'require',
                'low_range|分值范围（最低分）' => 'require',
                'high_range|分值范围（最高分）' => 'require',
                'is_show|是否显示' => 'require',
                'overview|等级概述' => 'require',
                'explain|等级释义' => 'require',
            ]);
            $RatingScaleFactorLevel = new RatingScaleFactorLevelModel();
            $RatingScaleFactorLevel->insert($param);
            return success([],'添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑因子等级
     * @return false|string
     */
    public function updateFactorLevel(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'mode_id|模板ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'factor_id|因子' => 'require',
                'level|程度等级' => 'require',
                'low_range|分值范围（最低分）' => 'require',
                'high_range|分值范围（最高分）' => 'require',
                'is_show|是否显示' => 'require',
                'overview|等级概述' => 'require',
                'explain|等级释义' => 'require',
            ]);
            $RatingScaleFactorLevel = new RatingScaleFactorLevelModel();
            $info = $RatingScaleFactorLevel->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save($param);
            return success([],'更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除因子等级
     * @return false|string
     */
    public function delFactorLevel(): bool|string
    {
        $id = $this->request->param('id');
        try {
            $RatingScaleFactorLevel = new RatingScaleFactorLevelModel();
            $RatingScaleFactorLevel->where('id','=',$id)->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success([],'删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 获取预警等级设置详情
     * @return false|string
     */
    public function getFactorWarningInfo(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $RatingScaleFactorWarning = new RatingScaleFactorWarningModel();
            return success($RatingScaleFactorWarning->find($id));
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 预警等级设置列表
     * @return false|string
     */
    public function factorWarningList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (isset($param['rating_scale_id']) && $param['rating_scale_id']){
                $where[] = ['rating_scale_id','=',$param['rating_scale_id']];
            }
            if (isset($param['mode_id']) && $param['mode_id']){
                $where[] = ['mode_id','=',$param['mode_id']];
            }
            $where[] = ['type','<',3];
            $RatingScaleService = new RatingScaleService($this->app);
            $factorArr = $RatingScaleService->getFactorLevel();
            $colorArr = $RatingScaleService->getFactorWarningColor();
            $markArr = $RatingScaleService->getFactorWarningMark();
            $RatingScaleFactorWarningModel = new RatingScaleFactorWarningModel();
            $data = $RatingScaleFactorWarningModel->where($where)
                ->with(['factorName'])
                ->paginate($param['pageSize'])->toArray();
            foreach ($data['data'] as &$item) {
                $item['sign_code'] = $markArr[$item['mark_id']]??'';
                $item['mark_color'] = $colorArr[$item['mark_color_id']]??'';
                if ($item['type'] == 1) {
                    $item['condition1'] = $item['factor_name']??'';
                    $item['condition2'] = $factorArr[$item['condition1_level']]??'';
                } elseif ($item['type'] == 2) {
                    $item['condition1'] = $factorArr[$item['factor_level']]?$factorArr[$item['factor_level']] . '因子':'';
                    $item['condition2'] = $item['condition2_level_count'];
                }
            }
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 新增预警等级设置
     * @return false|string
     */
    public function addFactorWarning(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'mode_id|模板ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'name|预警名称' => 'require',
                'type|计分方式' => 'require',
                'is_use|启用状态' => 'require',
                'sign|运算符号' => 'require',
                'factor_id|因子' => 'require',
                'condition1_level|预警达成条件' => 'require',
                'mark_id|标志样式' => 'require',
                'mark_count|标志数量' => 'require',
                'mark_color_id|标志颜色' => 'require',
            ]);
            $RatingScaleFactorWarning = new RatingScaleFactorWarningModel();
            $RatingScaleFactorWarning->insert($param);
            return success([],'添加成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 编辑预警等级设置
     * @return false|string
     */
    public function updateFactorWarning(): bool|string
    {
        try {
            $param = $this->request->param();
            $this->validate($param,[
                'id|ID' => 'require',
                'mode_id|模板ID' => 'require',
                'rating_scale_id|量表ID' => 'require',
                'name|预警名称' => 'require',
                'type|计分方式' => 'require',
                'is_use|启用状态' => 'require',
                'sign|运算符号' => 'require',
                'factor_id|因子' => 'require',
                'condition1_level|预警达成条件' => 'require',
                'mark_id|标志样式' => 'require',
                'mark_count|标志数量' => 'require',
                'mark_color_id|标志颜色' => 'require',
            ]);
            $RatingScaleFactorWarning = new RatingScaleFactorWarningModel();
            $info = $RatingScaleFactorWarning->find($param['id']);
            if (!$info) throw new \Exception('参数错误！');
            $info->save($param);
            return success([],'更新成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 删除预警等级设置
     * @return false|string
     */
    public function delFactorWarning(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $RatingScaleFactorWarning = new RatingScaleFactorWarningModel();
            $RatingScaleFactorWarning->where('id','=',$id)->update([
                'is_del' => 1,
                'del_time' => time()
            ]);
            return success([],'删除成功！');
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 区域量表
     * @return bool|string
     */
    public function RegionalScaleList(): bool|string
    {
        try {
            $param = $this->request->param();
            $where = [];
            if (!empty($param['name'])){
                $where[] = ['name','like','%'.$param['name'].'%'];
            }
            if (!empty($param['start_time']) && !empty($param['end_time'])) {
                $where[] = ['time', 'between', [$param['start_time'], $param['end_time']]];
            }else{
                if (!empty($param['start_time'])) {
                    $where[] = ['time', '>=', $param['start_time']];
                }
                if (!empty($param['end_time'])) {
                    $where[] = ['time', '<=', $param['end_time']];
                }
            }
            if (!empty($param['level'])){
                $UserModel = new UserModel();
                $uid = $UserModel->where([
                    ['level','=',$param['level']],
                    ['company_id','=',$this->userData['company_id']],
                    ['type','=',2]
                ])->column('id');
                if (count($uid)){
                    $where[] = ['uid','in',$uid];
                }else{
                    $where[] = ['id','=',-1];
                }
            }
            $where[] = ['company_id','=',$this->userData['company_id']];
            $where[] = ['channel','=',3];
            $query = $this->mode->where($where);
            $data = $query->with(['user'])->order('id desc')->paginate($param['pageSize'])->toArray();
            $data['ids'] = $query->column('id');
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 区域量表-是否隐藏
     * @return bool|string
     */
    public function regionalScaleStatus(): bool|string
    {
        try {
            $id = $this->request->param('id');
            $status = $this->request->param('status');
            if (is_array($id)){
                $this->mode->where('id','in',$id)->update(['status'=>$status]);
            }else{
                $info = $this->mode->find($id);
                if (!$info) throw new \Exception('参数错误！');
                $info->status = $status;
                $info->save();
            }
            return success();
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }

    /**
     * 区域量表-用户类型选择器
     * @return bool|string
     */
    public function regionalScaleRoleSelector(): bool|string
    {
        try {
            $data = [
                [
                    'id' => 1,
                    'name' => '省级平台管理员（L1）'
                ],
                [
                    'id' => 2,
                    'name' => '市级平台管理员（L2）'
                ],
                [
                    'id' => 3,
                    'name' => '区县级平台管理员（L3）'
                ],
            ];
            return success($data);
        } catch (\Exception $e) {
            return error($e->getMessage(), $e->getCode(),[
                'line' => $e->getLine(),
                'file' => $e->getFile(),
            ]);
        }
    }


}
